package org.blogwu.learn.designpattern.建造结合责任链;

import org.apache.commons.lang3.StringUtils;
import org.blogwu.learn.designpattern.建造结合责任链.handle.AuthHandler;
import org.blogwu.learn.designpattern.建造结合责任链.handle.Handler;
import org.blogwu.learn.designpattern.建造结合责任链.handle.LoginHandler;
import org.blogwu.learn.designpattern.建造结合责任链.handle.ValidateHandler;

public class MemberService {

    /**
     * 传统构建者
     * @param loginName
     * @param loginPass
     */
    public void oldLogin(String loginName, String loginPass) {

        if (StringUtils.isEmpty(loginName) ||
                StringUtils.isEmpty(loginPass)) {
            System.out.println("用户名和密码为空");
            return;
        }

        System.out.println("用户名和密码不为空，可以往下执行");

        Member member = checkExists(loginName, loginPass);
        if (null == member) {
            System.out.println("用户不存在");
            return;
        }
        System.out.println("登录成功！");

        if (!"管理员".equals(member.getRoleName())) {
            System.out.println("您不是管理员，没有操作权限");
            return;
        }
        System.out.println("允许操作");

    }


    /**
     * 责任链重构
     *
     * @param loginName
     * @param loginPass
     */
    public void newLogin(String loginName, String loginPass) {
        Handler validateHandler = new ValidateHandler();
        Handler loginHandler = new LoginHandler();
        Handler authHandler = new AuthHandler();

        Member member = new Member(loginName, loginPass);

        //  validate -> login -> auth
        validateHandler.next(loginHandler);
        loginHandler.next(authHandler);
        validateHandler.doHandler(member);

        //  auth -> login -> validate
//        authHandler.next(loginHandler);
//        loginHandler.next(validateHandler);
//        member.setRoleName("管理员");
//        authHandler.doHandler(member);
    }


    /**
     * 责任链+构建者模式
     * @param loginName
     * @param loginPass
     */
    public void loginAndBuild(String loginName, String loginPass) {

        Handler.Builder builder = new Handler.Builder();

        builder.addHandler(new ValidateHandler())
                .addHandler(new LoginHandler())
                .addHandler(new AuthHandler());

        builder.build().doHandler(new Member(loginName, loginPass));

    }


    private Member checkExists(String loginName, String loginPass) {
        Member member = new Member(loginName, loginPass);
        member.setRoleName("管理员");
        return member;
    }

    public static void main(String[] args) {
        MemberService service = new MemberService();
        service.loginAndBuild("tom", "666");
    }


}
